package cn.yeziji.forum.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

/**
 * Spring 容器工具类
 *
 * @author gzkemays
 * @since 2021/12/11 18:03
 */
@Component
public class SpringUtils implements BeanFactoryPostProcessor {
  /** Spring应用上下文环境 */
  private static ConfigurableListableBeanFactory beanFactory;

  @Override
  public void postProcessBeanFactory(
      ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
    SpringUtils.beanFactory = configurableListableBeanFactory;
  }
  /**
   * 获取对象
   *
   * @param name bean 名称
   * @return Object 一个以所给名字注册的bean的实例
   */
  @SuppressWarnings("unchecked")
  public static <T> T getBean(String name) {
    return (T) beanFactory.getBean(name);
  }

  /**
   * 获取类型为requiredType的对象
   *
   * @param clazz bean 对象
   * @return 对象
   */
  public static <T> T getBean(Class<T> clazz) {
    return beanFactory.getBean(clazz);
  }
}
